package com.hsb.seckill.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.hsb.seckill.entity.Order;
import com.hsb.seckill.entity.SeckillOrder;
import com.hsb.seckill.entity.User;
import com.hsb.seckill.result.ResBean;
import com.hsb.seckill.result.ResBeanEnum;
import com.hsb.seckill.service.GoodsService;
import com.hsb.seckill.service.OrderService;
import com.hsb.seckill.vo.GoodsVo;
import com.hsb.seckill.vo.SeckillMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 消息消费者
 */
@Service
@Slf4j
public class MQReceiver {

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderService orderService;

    @RabbitListener(queues = "seckillQueue")
    public void receiverSeckillMessage(String msg){
        //log.info("接收秒杀消息："+ msg);

        SeckillMessage seckillMessage = JSON.parseObject(msg, SeckillMessage.class);
        User user = seckillMessage.getUser();
        Long goodsId = seckillMessage.getGoodsId();
        GoodsVo goods = goodsService.querySeckillGoodsById(goodsId);

        //// 从redis获取订单,判断是否有重复用户抢购
        //SeckillOrder seckillOrder = (SeckillOrder) redisTemplate.opsForValue().get("order:" + user.getId() + ":" + goodsId);
        //if (seckillOrder != null){
        //    return;
        //}
        //判断库存
        if (goods.getStockCount()<1){
            return;
        }
        //进行秒杀，创建订单
        Order order = orderService.sekill(user,goods);
    }

    ////hello模式
    //@RabbitListener(queues = "queue")
    //public void receiverHello(Object msg){
    //    log.info("接收消息："+msg);
    //}
    //
    ////fanout模式
    //@RabbitListener(queues = "fanout01")
    //public void receiverFanout01(Object msg){
    //    log.info("接收消息："+msg);
    //}
    //@RabbitListener(queues = "fanout02")
    //public void receiverFanout02(Object msg){
    //    log.info("接收消息："+msg);
    //}
    //
    ////direct模式
    //@RabbitListener(queues = "direct01")
    //public void receiverDirect01(Object msg){
    //    log.info("接收消息："+msg);
    //}
    //
    //@RabbitListener(queues = "direct02")
    //public void receiverDirect02(Object msg){
    //    log.info("接收消息："+msg);
    //}
    //
    ////topIC模式
    //@RabbitListener(queues = "topic01")
    //public void receiverTopic01(Object msg){
    //    log.info("接收消息："+msg);
    //}
    //
    //@RabbitListener(queues = "topic02")
    //public void receiverTopic02(Object msg){
    //    log.info("接收消息："+msg);
    //}
}
